<?php
namespace backend\controllers;

use backend\models\CoordinationDegree;
use backend\models\EnterpriseGrade;
use backend\models\FollowType;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\models\ClueOrgin;
use backend\models\CompanyCats;


/**
 * Clue controller
 */
class ParamsController extends Controller
{
    public $enableCsrfValidation = false;//开启防止crf攻击
    //public $layout='base';
    /**
     * @inheritdoc
     */

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * 系统设置的首页
     */
    public function actionIndex()
    {

    }

    /**
     * 到线索参数页
     */
    public function actionParams(){
        $clueOrginList=ClueOrgin::getClueOrgin();
        $clueFollowTypeList=FollowType::getFollowTypeList(1);
        $companyCatsList=CompanyCats::getCompanyCatsList();
        $gradeList=EnterpriseGrade::getEnterpriseGrade();
        $enterFollowTypeList=FollowType::getFollowTypeList(2);
        $followTypeList=FollowType::getFollowTypeList(3);
        $coordinationList=CoordinationDegree::getCoordinationDegreeList();

        $data=array();
        $data['clueFollowTypeList']=$clueFollowTypeList;
        $data['companyCatsList']=$companyCatsList;
        $data['gradeList']=$gradeList;
        $data['enterFollowTypeList']=$enterFollowTypeList;
        $data['followTypeList']=$followTypeList;
        $data['coordinationList']=$coordinationList;
        $data['clueOrginList']=$clueOrginList;

        return $this->renderPartial('index',$data);

    }
    /**
     * excel导入
     */
    public function actionToImport(){
        return $this->render('exceltpl');
    }

    /**
     * excel导出
     */
    public function actionImport() {
        header("Content-type: text/html; charset=utf-8");
        set_time_limit(0);
        ini_set('memory_limit','256M');
        require '../extensions/PHPExcel.php';        //引入PHPExcel
        $request = Yii::$app->request;
        $data = array();
        if($_POST){
            if($_FILES["file"]["error"] > 0){
                $data = array('error'=>'1','msg'=>'文件上传失败,请重新上传..','info'=>'');
            }
            $excelFile = '';    //文件名
            $filepath = "upload/excel";
            $allowtype=array("xls");
            $arr=explode(".", $_FILES["file"]["name"]);
            $hz=strtolower($arr[count($arr)-1]);

            if(!is_dir($filepath)) { mkdir($filepath, 0777); chmod($filepath, 0777);}

            $randname = date("Y").date("m").date("d").date("H").date("i").date("s").rand(1000, 9999).".".$hz;
            if(is_uploaded_file($_FILES["file"]["tmp_name"])){      //将临时位置的文件移动到指定的目录上即可
                if(move_uploaded_file($_FILES["file"]["tmp_name"], $filepath.'/'.$randname)){
                    $excelFile = $filepath.'/'.$randname;       //上传成功的节奏
                    chmod($excelFile, 0777);
                }
            }
            if(!$excelFile){        //文件不存在
                $data = array('error'=>'2','msg'=>'文件上传失败,请重新上传,检查文件名..','info'=>'');
            }else{      //读取Excel
                $phpexcel = new \PHPExcel;
                $excelReader = \PHPExcel_IOFactory::createReader('Excel5');
                $phpexcel = $excelReader->load($excelFile)->getSheet(0);//载入文件并获取第一个sheet
                $total_line = $phpexcel->getHighestRow();            //多少行
                $total_column = $phpexcel->getHighestColumn();       //多少列
                $info = array();
                $okk = array();
                $err = array();

                for($row = 1; $row <= $total_line; $row++) {
                    $oneUser = array();
                    for($column = 'A'; $column <= 'K'; $column++) {
                        $test[$row][]=trim($phpexcel->getCell($column.$row)->getValue());
                    }
                    }

                        var_dump($test);
                die;
                for($row = 2; $row <= $total_line; $row++) {
                    $oneUser = array();
                    for($column = 'A'; $column <= 'K'; $column++) {
                        $oneUser[] = trim($phpexcel->getCell($column.$row)->getValue());
                    }


                    $username = $oneUser[3];        //用户名
                    $pwd = $oneUser[4];             //密码
                    $existUser = MemberList::find()->where("username='{$username}'")->exists();
                    if($existUser){$err[] = $username.'###该用户名已被注册使用,请换一个';break; }

                    $memModel = new MemberList;
                    $memModel->username = $username;
                    $memModel->password = AuthUser::md9Password($pwd);
                    $memModel->vip_id = $oneUser[0];
                    $memModel->sale_id = $oneUser[1];
                    $memModel->staff_id = $oneUser[2];
                    $memModel->nickname = $oneUser[5];
                    $memModel->tel = $oneUser[6];
                    $memModel->sex = $oneUser[7];
                    $memModel->vip_type = $oneUser[8];
                    $memModel->vip_name = $oneUser[9];
                    $memModel->address = $oneUser[10];
                    $memModel->add_user = '';
                    $memModel->add_time = time();
                    $memModel->isNewRecord = true;
                    if(!$memModel->save()){
                        $err[] = $username.'###该用户添加失败,请检查';break;
                    }

                    $okk[] = $username.'###该用户导入成功!!!';
                }
                $info['err'] = $err;
                $info['okk'] = $okk;
                $data = array('error'=>'0','msg'=>'成功','info'=>$info);
            }
        }
        return $this->render('import',['data'=>$data]);
    }
        public function actionExport(){
            require '../extensions/PHPExcel.php';
            $objectPHPExcel = new \PHPExcel;
            $objectPHPExcel->setActiveSheetIndex(0);
            $objectPHPExcel->getActiveSheet()->setCellValue('B1','产品信息表');

            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B5','产品信息表');
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B2','产品信息表');


            /*foreach ( $data as $product )
            {
                if ( $n % $page_size === 0 )
                {
                    $current_page = $current_page +1;

                    //报表头的输出
                    $objectPHPExcel->getActiveSheet()->mergeCells('B1:G1');
                    $objectPHPExcel->getActiveSheet()->setCellValue('B1','产品信息表');

                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B2','产品信息表');
                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B2','产品信息表');
                    $objectPHPExcel->setActiveSheetIndex(0)->getStyle('B1')->getFont()->setSize(24);
                    $objectPHPExcel->setActiveSheetIndex(0)->getStyle('B1')
                        ->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B2','日期：'.date("Y年m月j日"));
                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G2','第'.$current_page.'/'.$page_count.'页');
                    $objectPHPExcel->setActiveSheetIndex(0)->getStyle('G2')
                        ->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);

                    //表格头的输出
                    $objectPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B3','编号');
                    $objectPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(6.5);
                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C3','名称');
                    $objectPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(17);
                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D3','生产厂家');
                    $objectPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(22);
                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E3','单位');
                    $objectPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F3','单价');
                    $objectPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
                    $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G3','在库数');
                    $objectPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);

                    //设置居中
                    $objectPHPExcel->getActiveSheet()->getStyle('B3:G3')
                        ->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

                 /*   //设置边框
                    $objectPHPExcel->getActiveSheet()->getStyle('B3:G3' )
                        ->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $objectPHPExcel->getActiveSheet()->getStyle('B3:G3' )
                        ->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $objectPHPExcel->getActiveSheet()->getStyle('B3:G3' )
                        ->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $objectPHPExcel->getActiveSheet()->getStyle('B3:G3' )
                        ->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $objectPHPExcel->getActiveSheet()->getStyle('B3:G3' )
                        ->getBorders()->getVertical()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

                    //设置颜色
                    $objectPHPExcel->getActiveSheet()->getStyle('B3:G3')->getFill()
                        ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF66CCCC');

                }
                //明细的输出
                $objectPHPExcel->getActiveSheet()->setCellValue('B'.($n+4) ,$product->id);
                $objectPHPExcel->getActiveSheet()->setCellValue('C'.($n+4) ,$product->product_name);
                $objectPHPExcel->getActiveSheet()->setCellValue('D'.($n+4) ,$product->product_agent->name);
                $objectPHPExcel->getActiveSheet()->setCellValue('E'.($n+4) ,$product->unit);
                $objectPHPExcel->getActiveSheet()->setCellValue('F'.($n+4) ,$product->unit_price);
                $objectPHPExcel->getActiveSheet()->setCellValue('G'.($n+4) ,$product->library_count);
                //设置边框
                $currentRowNum = $n+4;
                $objectPHPExcel->getActiveSheet()->getStyle('B'.($n+4).':G'.$currentRowNum )
                    ->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                $objectPHPExcel->getActiveSheet()->getStyle('B'.($n+4).':G'.$currentRowNum )
                    ->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                $objectPHPExcel->getActiveSheet()->getStyle('B'.($n+4).':G'.$currentRowNum )
                    ->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                $objectPHPExcel->getActiveSheet()->getStyle('B'.($n+4).':G'.$currentRowNum )
                    ->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                $objectPHPExcel->getActiveSheet()->getStyle('B'.($n+4).':G'.$currentRowNum )
                    ->getBorders()->getVertical()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                $n = $n +1;
            }

            //设置分页显示
            //$objectPHPExcel->getActiveSheet()->setBreak( 'I55' , PHPExcel_Worksheet::BREAK_ROW );
            //$objectPHPExcel->getActiveSheet()->setBreak( 'I10' , PHPExcel_Worksheet::BREAK_COLUMN );
            $objectPHPExcel->getActiveSheet()->getPageSetup()->setHorizontalCentered(true);
            $objectPHPExcel->getActiveSheet()->getPageSetup()->setVerticalCentered(false);
            */

            ob_end_clean();
            ob_start();

            header('Content-Type : application/vnd.ms-excel');
            header('Content-Disposition:attachment;filename="'.'产品信息表-'.date("Y年m月j日").'.xls"');
            $objWriter=\PHPExcel_IOFactory::createWriter($objectPHPExcel,'Excel5');
            $objWriter->save('php://output');
            die;
        }
    /**
     * 添加公司类型列表
     */
    public function actionAddCompanyCatsed(){

        $id=2;

        if($id>0){
            $companyCats=CompanyCats::find()->where(['id'=>$id])->one();
            if(empty($companyCats)){
                returnResult(100017,'找不到记录');
            }
        }else{
            $companyCats=new CompanyCats();
        }
        $companyCats->typeName='公司333';
        $companyCats->sort=0;
        $companyCats->addTime=time();
        $doResult=$companyCats->save();
        if(!empty($doResult)){
            returnResult(0,'操作公司分类成功');
        }else{
            returnResult(100018,'操作公司类型失败');
        }

    }
    /**
     * 添加线索来源
     */
    public function actionEditClueOrgined(){
        $id=2;

        if($id>0){
            $clueOrgin=ClueOrgin::find()->where(['id'=>$id])->one();
            if(empty($clueOrgin)){
                returnResult(100018,'找不到记录');
            }
        }else{
            $clueOrgin=new ClueOrgin();
        }
        $clueOrgin->name='公司333';
        $clueOrgin->sort=0;
        $clueOrgin->type=1;
        $doResult=$clueOrgin->save();
        if(!empty($doResult)){
            returnResult(0,'操作线索来源成功');
        }else{
            returnResult(100018,'操作线索来源失败');
        }
    }
    /**
     * 添加跟进类型
     */
    public function actionEditFollowTyped(){
        $id=0;

        if($id>0){
            $followType=FollowType::find()->where(['id'=>$id])->one();
            if(empty($followType)){
                returnResult(100018,'找不到记录');
            }
        }else{
            $followType=new FollowType();
        }
        $followType->name='公司333';
        $followType->statusId=1;
        $followType->sort=0;
        $followType->type=1;
        $doResult=$followType->save();
        if(!empty($doResult)){
            returnResult(0,'操作跟进类型成功');
        }else{
            returnResult(100018,'操作跟进类型失败');
        }
    }
    /**
     * 添加配合度
     */
    public function actionEditCoordinationDegree(){
        $id=0;

        if($id>0){
            $coordinationDegree=CoordinationDegree::find()->where(['id'=>$id])->one();
            if(empty($coordinationDegree)){
                returnResult(100022,'找不到记录');
            }
        }else{
            $coordinationDegree=new CoordinationDegree();

        }

        $coordinationDegree->name='公司333';

        $coordinationDegree->sort=0;

        $doResult=$coordinationDegree->save();
        if(!empty($doResult)){
            returnResult(0,'操作配合度成功');
        }else{
            returnResult(100023,'操作配合度失败');
        }
    }
    /**
     * 删除参数
     */
    public function actionDeleteParams(){
        $params=Yii::$app->request->post();
        $id=getData($params['id'],'系统繁忙');
        $type=getData($params['type'],'请指定类型');
        $object=$this->getParamsObject($type);
        $doResult=$object::findOne(['id'=>$id])->delete();
        if($doResult){
            returnResult(0,'删除成功');
        }else{
            returnResult(100049,'删除失败');
        }
    }
    /**
     * 添加参数
     */
    public function actionAddParams(){
        $params=Yii::$app->request->post();
        //$id=getData($params['id'],'系统繁忙');
        $type=getData($params['type'],'请指定类型');
        $name=getData($params['name'],'请填写内容');
        $object=$this->getParamsObject($type);
        $object=new $object();
        if($type==3){
            $object->typeName=$name;
        }else if($type==2){

            $object->name=$name;
            $object->type=1;
        }else if($type==5){

            $object->name=$name;
            $object->type=2;
        }else if($type==6){

            $object->name=$name;
            $object->type=3;
        }else{
            $object->name=$name;
        }

        $doResult=$object->save();
        if($doResult){
            returnResult(0,'保存成功');
        }else{
            returnResult(100049,'保存失败');
        }
    }
    /**
     * 获取参数对应的对象
     */
    public function getParamsObject($type){
        if($type==1){
            $object=ClueOrgin::className();
        }else if($type==2){
            $object=FollowType::className();
        }else if($type==3){
            $object=CompanyCats::className();
        }else if($type==4){
            $object=EnterpriseGrade::className();
        }else if($type==5){
            $object=FollowType::className();
        }else if($type==6){
            $object=FollowType::className();
        }else if($type==7){
            $object=CoordinationDegree::className();
        }else{
            returnResult(100048,'对象不存在');
        }
        return $object;
    }
}
